package org.example.proxy.jdk;

import java.io.*;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Modifier;
import java.security.AccessController;
import java.security.PrivilegedAction;

/**
 * @author : RXK
 * Date : 2021/5/28 16:05
 * Code Less Think More
 * Desc: 自定义类加载器
 */
public class CustomerClassLoader extends ClassLoader {


    private String path;

    public CustomerClassLoader(String path) {
        this.path = path;
    }

    /**
     * 加载指定的字节码文件
     *
     * @param name ：字节码文件的全路径
     * @return ：加载到的类
     * @throws ClassNotFoundException
     */
    @Override
    protected Class<?> findClass(String name) throws ClassNotFoundException {
        System.out.println("当前的name是：{" + name + "}");

        //由全路径获取class字节码文件 名称
        String classFileName = getFile(name);

        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(65535);
        int read;
        //读取指定路径下的class文件
        try (BufferedInputStream bufferedInputStream = new BufferedInputStream(new FileInputStream(path + File.pathSeparator + classFileName))) {
            while ((read = bufferedInputStream.read()) != -1) {
                byteArrayOutputStream.write(read);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        return defineClass(classFileName, byteArrayOutputStream.toByteArray(), 0, byteArrayOutputStream.size());
    }


    // xx.class
    private String getFile(String name) {
        if (name.contains(".")) {
            int indexOf = name.lastIndexOf(".");
            return name.substring(indexOf + 1);
        } else {
            return name + ".class";
        }
    }
}
